<template>
  <view class="login-container">
    <view class="logo">
      <image src="/static/logo.png" mode="widthFix"></image>
      <text class="title">虚拟号码通话系统</text>
    </view>
    
    <view class="login-form">
      <view class="form-group">
        <input 
          type="text" 
          v-model="username" 
          placeholder="请输入用户名" 
          class="input"
          @input="handleInput"
        />
      </view>
      
      <!-- 密码输入组件 -->
      <view class="form-group">
        <password-input 
          v-model="password" 
          placeholder="请输入密码" 
          :refresh-key="refreshKey"
          @toggle="handleToggle"
        />
      </view>
      
      <view class="form-group verify-group">
        <input 
          type="text" 
          v-model="verifyCode" 
          placeholder="请输入验证码" 
          class="input verify-input"
          @input="handleInput"
        />
        <canvas 
          class="verify-canvas" 
          canvas-id="verifyCanvas"
          @click="generateVerifyCode"
          style="width: 180px; height: 70px;"
        ></canvas>
      </view>
      
      <button class="login-btn" @click="login" :disabled="isSubmitting">
        {{ isSubmitting ? '登录中...' : '登录' }}
      </button>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import PasswordInput from '@/components/password-input/password-input.vue';

// 表单数据
const username = ref('');
const password = ref('');
const verifyCode = ref('');
const correctVerifyCode = ref('');
const isSubmitting = ref(false);
const refreshKey = ref(0); // 用于强制组件刷新的key

// 页面加载时初始化验证码
onLoad(() => {
  generateVerifyCode();
});

// 处理密码框切换事件，强制刷新组件
const handleToggle = () => {
  refreshKey.value++;
};

const handleInput = () => {};

// 生成验证码
const generateVerifyCode = () => {
  const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz0123456789';
  let code = '';
  for (let i = 0; i < 4; i++) {
    code += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  correctVerifyCode.value = code;
  
  const ctx = wx.createCanvasContext('verifyCanvas');
  ctx.setFillStyle('#f3f3f3');
  ctx.fillRect(0, 0, 180, 70);
  
  // 绘制干扰线
  for (let i = 0; i < 3; i++) {
    ctx.setStrokeStyle(getRandomColor());
    ctx.beginPath();
    ctx.moveTo(Math.random() * 180, Math.random() * 70);
    ctx.lineTo(Math.random() * 180, Math.random() * 70);
    ctx.stroke();
  }
  
  // 绘制干扰点
  for (let i = 0; i < 20; i++) {
    ctx.setFillStyle(getRandomColor());
    ctx.beginPath();
    ctx.arc(Math.random() * 180, Math.random() * 70, 1, 0, 2 * Math.PI);
    ctx.fill();
  }
  
  // 绘制验证码文字
  ctx.setFontSize(26);
  for (let i = 0; i < 4; i++) {
    ctx.setFillStyle(getRandomColor());
    const rotate = (Math.random() - 0.5) * 0.3;
    ctx.save();
    ctx.translate(30 + i * 35, 45);
    ctx.rotate(rotate);
    ctx.fillText(code.charAt(i), 0, 0);
    ctx.restore();
  }
  
  ctx.draw();
};

// 生成随机颜色
const getRandomColor = () => {
  const r = Math.floor(Math.random() * 100) + 30;
  const g = Math.floor(Math.random() * 100) + 30;
  const b = Math.floor(Math.random() * 100) + 30;
  return `rgb(${r}, ${g}, ${b})`;
};

// 登录逻辑（核心修改：使用userId作为标识）
const login = async () => {
  // 表单验证
  if (!username.value.trim()) {
    uni.showToast({ title: '请输入用户名', icon: 'none' });
    return;
  }
  
  if (!password.value.trim()) {
    uni.showToast({ title: '请输入密码', icon: 'none' });
    return;
  }
  
  if (!verifyCode.value.trim() || verifyCode.value.toLowerCase() !== correctVerifyCode.value.toLowerCase()) {
    uni.showToast({ title: '验证码错误', icon: 'none' });
    generateVerifyCode();
    return;
  }
  
  try {
    isSubmitting.value = true;
    uni.showLoading({ title: '登录中...', mask: true });
    
    // 调用登录接口
    const res = await uni.request({
      url: 'http://localhost:6006/user-client/api/loginInfo/login',
      method: 'POST',
      data: {
        account: username.value.trim(),
        password: password.value.trim()
      },
      timeout: 10000
    });
    
    uni.hideLoading();
    isSubmitting.value = false;
    
    // 网络错误处理
    if (res.errMsg && res.errMsg.includes('fail')) {
      uni.showToast({ title: '网络错误: ' + res.errMsg, icon: 'none' });
      return;
    }
    
    // HTTP状态码错误处理
    if (res.statusCode !== 200) {
      uni.showToast({ title: `请求失败: ${res.statusCode}`, icon: 'none' });
      return;
    }
    
    const result = res.data;
    // 登录成功处理（核心修改：校验userId而非id）
    if (result.code === 0) {
      // 确保返回的用户信息包含userId（后端实际返回的标识）
      if (!result.data || !result.data.userId) {
        uni.showToast({ title: '登录信息不完整', icon: 'none' });
        console.error('登录成功但用户信息缺少userId:', result.data);
        return;
      }
      
      // 存储完整的登录状态（使用userId作为核心标识）
      uni.setStorageSync('userInfo', result.data); // 包含userId的用户信息
      uni.setStorageSync('isLogin', true); // 登录状态标记
      uni.showToast({ title: '登录成功', icon: 'success' });
      
      // 跳转首页
      setTimeout(() => {
        uni.switchTab({ url: '/pages/index/index' });
      }, 1000);
    } else {
      // 登录失败（账号密码错误等）
      uni.showToast({ title: result.msg || '登录失败', icon: 'none' });
      generateVerifyCode();
    }
  } catch (error) {
    // 异常处理
    uni.hideLoading();
    isSubmitting.value = false;
    uni.showToast({ title: '登录异常', icon: 'none' });
    console.error('登录异常:', error);
    generateVerifyCode();
  }
};
</script>

<style scoped>
.login-container {
  display: flex;
  flex-direction: column;
  padding: 40rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.logo {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 80rpx 0;
}

.logo image {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 30rpx;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.login-form {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.form-group {
  background-color: #fff;
  border-radius: 8rpx;
  padding: 0 20rpx;
}

.input {
  width: 100%;
  height: 100rpx;
  font-size: 32rpx;
  border-bottom: 1px solid #eee;
}

.input:last-child {
  border-bottom: none;
}

.verify-group {
  display: flex;
  align-items: center;
  padding: 15rpx 20rpx;
  height: 100rpx;
}

.verify-input {
  flex: 1;
  border-bottom: none;
  height: 70rpx;
}

.verify-canvas {
  margin-left: 20rpx;
  border-radius: 8rpx;
  overflow: visible;
}

.login-btn {
  width: 100%;
  height: 100rpx;
  line-height: 100rpx;
  background-color: #007AFF;
  color: #fff;
  font-size: 34rpx;
  border-radius: 8rpx;
  margin-top: 40rpx;
}

.login-btn:disabled {
  background-color: #999;
  opacity: 0.8;
}
</style>